var tableSearchUrl;

var currentPage; 

$(document).ready(function()
{
    TableAfterLoadTrigger();
    
    $(".button").button();    
    
    $('.ui-fake-button').hover(function(){$(this).toggleClass('ui-state-highlight')});    
});

function createDialog(url)
{
  $.get(url, null, function(response){
    $('.dialog').append(response);
  });
}

$.fn.imageDelete = function(table, id)
{
  var $this = this;
  
  $.post(tableUrl + 'form/media_delete_one',
  {
    id: id,
    table: table
  }, 
  function()
  {
    $($this).parents('li').remove();
  })
}

function mediaDescriptionWindow(fieldId, fileId)
{
  $.post(tableUrl + 'form/media_description_window',
  {
    fieldId: fieldId,
    fileId: fileId
  }, 
  function(response)
  {
    $('.dialog').append(response);
  })
}

function mediaDescriptionSave(description, fieldId, fileId)
{
  $.post(tableUrl + 'form/media_description_save',
  {
    description: description,
    fieldId: fieldId,
    fileId: fileId
  }, 
  function(response)
  {
    $('li.field-' + fieldId + '#' + fileId).replaceWith(response);
  })
}

$.fn.TableRequestsHandler = function(userParams)
{ 
    var $this = this;
    
    var defaultParams = 
    {
      requestUrl: tableSearchUrl,
      targetElement : 'table.main tbody',
      page: 1
    }
    
    var params = $.extend({}, defaultParams, userParams); 
    
    var data = new Object();
    
    data.table = table;
    data.page = params.page;
    
    data.fields = new Array();   
    
    var i = 0;
    
    $('.table-search-widget').each(function()
    {
      if($(this).hasClass('datapicker-wrapper'))
      {
        if($(this).find('input[type="date_from"]').val() != '' || $(this).find('input[type="date_to"]').val() != '')
        {
          data.fields[i] = new Object();

          if($(this).find('input[type="date_from"]').val() != '')
          {
            data.fields[i].value_from = $(this).find('input[type="date_from"]').val();
          }
          if($(this).find('input[type="date_to"]').val() != '')
          {
            data.fields[i].value_to = $(this).find('input[type="date_to"]').val();
          } 

          data.fields[i].type = $(this).attr('type');
          data.fields[i].subtype = $(this).attr('subtype');
          data.fields[i].columnName = $(this).attr('name');
          i++;
        }
      }     
      else
      {
        if($(this).val() != '')
        {
          data.fields[i] = new Object();
          data.fields[i].value = $(this).val();
          data.fields[i].type = $(this).attr('type');
          data.fields[i].subtype = $(this).attr('subtype');
          data.fields[i].columnName = $(this).attr('name');

          if($(this).attr('type') == 'choice')
          {
             data.fields[i].relationName = $(this).attr('relationName');
          }

          i++;
        }      
      }
      
    });
   
   $.post(params.requestUrl, data, function(response)
   {
     $('.pagination').replaceWith(response.pagination);
     
     $(params.targetElement).replaceWith(response.rows);
     
     TableAfterLoadTrigger();
     
     if($($this).val() && $($this).attr('type') == 'text')
     {
         $('td[name="'+$($this).attr('name')+'"]').highlight($($this).val());
     }
     
   },
   'json');  
}

function TableAfterLoadTrigger()
{
  initLytebox();  

  $(".sortable").sortable({
      handle: '.ui-icon', 
      axis : 'y',
      update: function(event, ui)
      {
          $.post(tableUrl + 'set_position', {
            'table' : table,
            'tableOrderArray': $(this).sortable("toArray"),
            'currentPage': currentPage
          });
      }

  });
  
  $( "table.main .datepicker" ).datepicker(
  { 
    dateFormat: 'yy-mm-dd'
  });
}

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};